package com.neusoft.utils;

import java.lang.reflect.Field;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: duan
 * @Date: Create in 15:20 2020/10/22
 */
public class ClassUtil {
    public static String generateInsertSqlFromObject(Object obj, String tableName) {
        Class cls = obj.getClass();
        Field[] fs = cls.getDeclaredFields();
        StringBuilder sb = new StringBuilder("insert into ");
        sb.append(tableName);
        sb.append("(");
        for (Field item : fs) {
            sb.append(camel2_(item.getName()));
            sb.append(",");
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append(") values(");
        for (Field item : fs) {
            sb.append("?,");
        }
        sb.deleteCharAt(sb.length() - 1);
        sb.append(")");

        return sb.toString();
    }

    /**
     * 获取对象中所有值，并以数组的形式返回
     * @param obj
     * @param tableName
     * @return
     */
    public static Object[] getValueArrayFromObject(Object obj) {
        Class cls = obj.getClass();
        Field[] fs = cls.getDeclaredFields();
        StringBuilder sb = new StringBuilder("insert into ");
        Object[] objs = new Object[fs.length];
        for (int i = 0; i < fs.length; i++) {
            Field item = fs[i];
            item.setAccessible(true);
            try {
                objs[i] = item.get(obj);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        return objs;
    }

    public static String camel2_(String str) {
        Pattern pattern = Pattern.compile("[A-Z]");
        Matcher matcher = pattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }

    public static void main(String[] args) {
//        Student bean = new Student();
//        bean.setId(0)
//            .setDormitory("404")
//            .setPassword("123")
//            .setPhone("11111111111")
//            .setSex("0")
//            .setUsername("haha");
//        System.out.println(generateInsertSqlFromObject(bean, "student"));
    }
}
